package linear.stack.base;

import java.util.Arrays;

/**
 * 顺序栈
 *
 * @author yeyangtao created at 16:49 2020/9/10
 */
public class MyArrayStack<T> implements MyStack<T> {
    private Object[] value;
    //栈中元素个数
    private int curr;
    //栈的大小
    private int size = 16;

    public MyArrayStack() {
        value = new Object[size];
    }

    public MyArrayStack(int capacity) {
        value = new Object[capacity];
        this.size = capacity;
    }

    @Override
    public void push(T x) {
        if (curr >= size) {
            size = size * 2;
            value = Arrays.copyOf(value, size);
        }
        value[curr++] = x;
    }

    public T pop() {
        if (curr == 0) return null;
        @SuppressWarnings("unchecked")
        T result = (T) value[--curr];
        return result;
    }

    @Override
    public T peek() {
        @SuppressWarnings("unchecked")
        T result = (T) value[curr - 1];
        return result;
    }

    @Override
    public boolean isEmpty() {
        return curr == 0;
    }

    @Override
    public int size() {
        return curr;
    }

    @Override
    public String toString() {
        if (value == null)
            return "null";
        int iMax = curr - 1;
        if (iMax == -1)
            return "[]";

        StringBuilder b = new StringBuilder();
        b.append('[');
        for (int i = 0; ; i++) {
            b.append(value[i]);
            if (i == iMax)
                return b.append(']').toString();
            b.append(", ");
        }
    }
}
